package cn.liumouren.jzxd.utils;

import cn.hutool.core.util.StrUtil;
import cn.liumouren.jzxd.common.utils.PageUtils;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.IService;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author Daniel Liu
 * @date 2021/1/31 17:50
 */
public class QueryUtil {
    /**
     * 分隔符号
     */
    private static final String SPLIT_STR = ",";
    private static final String CUR_STR = "cur";
    private static final String SIZE_STR = "size";
    private static final String SEARCH_COUNT_STR = "searchCount";
    private static final String WRAPPER_STR = "wrapper";
    private static final String ORDER_UP_STR = "up";
    private static final String ORDER_DOWN_STR = "down";
    private static final String SELECT_STR = "select";
    private static final String FIND_ALL_STR = "findAll";

    /**
     * 对like eq order进行处理
     *
     * @param keyMap
     * @param <T>
     * @return
     */
    public static <T> Map<String, Object> process(Map<String, Object> keyMap) {
        Map<String, String> likeMap = new HashMap<>(8);
        QueryWrapper<T> wrapper = new QueryWrapper<>();
        HashMap<String, Object> map = new HashMap<>(8);
        int cur = 1;
        int size = 10;
        boolean searchCount = false;
        boolean findAll = false;
        if (keyMap != null) {
            String key;
            Object value;
            for (Map.Entry<String, Object> entry : keyMap.entrySet()) {
                key = entry.getKey();
                value = entry.getValue();
                // 处理当前页数 默认 1
                if (CUR_STR.equals(key)) {
                    cur = Integer.parseInt((String) keyMap.get(CUR_STR));
                    cur = Math.max(cur, 1);
                    continue;
                }
                // 处理每页显示条数 默认 10
                if (SIZE_STR.equals(key)) {
                    size = Integer.parseInt((String) keyMap.get(SIZE_STR));
                    size = size < 1 ? 10 : size;
                    continue;
                }
                // 处理是否查询所有
                if (FIND_ALL_STR.equals(key)) {
                    if (value != null && Boolean.parseBoolean((String) value)) {
                        findAll = true;
                    }
                    continue;
                }
                // 处理是否查询记录条数
                if (SEARCH_COUNT_STR.equals(key)) {
                    if (value != null && Boolean.parseBoolean((String) value)) {
                        searchCount = true;
                    }
                    continue;
                }
                // ====================================================================
                // 下列情况可能出现 key重复查询 例如 "name":"小明" "name":"小%"
                // 此时一个key对象多个value, 所以对value进行分割
                String[] vs = ((String) value).split(SPLIT_STR);
                if (vs.length <= 0) {
                    continue;
                }
                // 处理select
                if (SELECT_STR.equals(key)) {
                    wrapper.select(vs);
                    continue;
                }
                for (String v : vs) {
                    if (StrUtil.isBlank(v)) {
                        continue;
                    }
                    // 处理order 升序
                    if (ORDER_UP_STR.equals(v)) {
                        wrapper.orderByAsc(key);
                        continue;
                    }
                    // 处理order 降序
                    if (ORDER_DOWN_STR.equals(v)) {
                        wrapper.orderByDesc(key);
                        continue;
                    }
                    // 处理like, 先将like提出来, 最后处理
                    if (v.startsWith("%") || v.endsWith("%")) {
                        likeMap.put(key, v);
                    } else {
                        // 处理eq
                        wrapper.eq(key, v);
                    }
                }
            }
        }
        // 处理like, like为 or 关系
        if (likeMap.size() > 0) {
            wrapper.and(wrapper1 -> {
                for (Map.Entry<String, String> entry : likeMap.entrySet()) {
                    String value = entry.getValue();
                    boolean isStart = value.startsWith("%");
                    boolean isEnd = value.endsWith("%");
                    if (isStart && isEnd) {
                        wrapper1.like(entry.getKey(), StrUtil.sub(value, 1, -1)).or();
                        break;
                    }
                    // 以%开头不以%结尾
                    if (isStart) {
                        wrapper1.likeLeft(entry.getKey(), value.substring(1)).or();
                        break;
                    }
                    // 以%结尾不以%开头
                    if (isEnd) {
                        wrapper1.likeRight(entry.getKey(), StrUtil.sub(value, 0, -1)).or();
                        break;
                    }
                }
            });
        }
        map.put(CUR_STR, cur);
        map.put(SIZE_STR, size);
        map.put(WRAPPER_STR, wrapper);
        map.put(SEARCH_COUNT_STR, searchCount);
        map.put(FIND_ALL_STR, findAll);
        return map;
    }

    public static <T> PageUtils getResult(IService<T> service, Map<String, Object> map) {
        map = QueryUtil.process(map);
        boolean findAll = (boolean) map.get(FIND_ALL_STR);
        @SuppressWarnings("unchecked")
        QueryWrapper<T> wrapper = (QueryWrapper<T>) map.get(WRAPPER_STR);
        if (findAll) {
            List<T> list = service.list(wrapper);
            return new PageUtils(list, list.size(), 0, 0);
        }
        int cur = (int) map.get(CUR_STR);
        int size = (int) map.get(SIZE_STR);
        boolean searchCount = (boolean) map.get(SEARCH_COUNT_STR);
        return new PageUtils(service.page(new Page<>(cur, size, searchCount), wrapper));
    }

}
